﻿/*
 * @author: wizardc
 */

using System;
using Unity.Collections.LowLevel.Unsafe;

namespace Dou.Utils
{
    /// <summary>
    /// 字节数组工具类
    /// </summary>
    public static class BytesUtil
    {
        /// <summary>
        /// 获取指定类型数组对应的字节数组
        /// </summary>
        public static unsafe byte[] Array2Bytes<T>(this T[] arr) where T : unmanaged
        {
            var len = arr.Length * sizeof(T);
            var bytes = new byte[len];
            fixed (T* p = &arr[0])
            {
                fixed (byte* b = &bytes[0])
                {
                    UnsafeUtility.MemCpy(b, p, len);
                }
            }
            return bytes;
        }

        /// <summary>
        /// 拷贝字节数组
        /// </summary>
        public static byte[] CloneBytes(byte[] source)
        {
            var bytes = new byte[source.Length];
            Buffer.BlockCopy(source, 0, bytes, 0, source.Length);
            return bytes;
        }
    }
}
